#include "sv2_video_streamer.h"
#include <cmath>
#include <fstream>
#ifdef WITH_GSTREAMER
#include "streamer_gstreamer_impl.h"
#endif
#ifdef WITH_FFMPEG
#include "x86_cuda/bs_push_streamer.h"
#endif

namespace sv2
{
  VideoStreamer::VideoStreamer()
  {
#ifdef WITH_GSTREAMER
    this->_gstreamer_impl = new VideoStreamerGstreamerImpl;
#endif
#ifdef WITH_FFMPEG
    this->_ffmpeg_impl = new BsPushStreamer;
#endif
  }
  VideoStreamer::~VideoStreamer()
  {
  }

  bool VideoStreamer::setupImpl()
  {
    cv::Size img_sz = this->getSize();
    int port = this->getPort();
    std::string url = this->getUrl();
    int bitrate = this->getBitrate();

#ifdef WITH_GSTREAMER
    return this->_gstreamer_impl->gstreamerSetup(this);
#endif
#ifdef WITH_FFMPEG
    std::string rtsp_url = "rtsp://127.0.0.1/live" + url;
#if defined(PLATFORM_X86_CUDA)
    std::string enc = "h264_nvenc";
#elif defined(PLATFORM_X86_INTEL)
    std::string enc = "h264_vaapi";
#endif
    return this->_ffmpeg_impl->setup(rtsp_url, img_sz.width, img_sz.height, 24, enc, bitrate);
#endif
    return false;
  }

  bool VideoStreamer::isOpenedImpl()
  {
#ifdef WITH_GSTREAMER
    return this->_gstreamer_impl->gstreamerIsOpened();
#endif
#ifdef WITH_FFMPEG
    return this->isRunning();
#endif
    return false;
  }

  void VideoStreamer::writeImpl(cv::Mat img_)
  {
#ifdef WITH_GSTREAMER
    this->_gstreamer_impl->gstreamerWrite(img_);
#endif
#ifdef WITH_FFMPEG
    this->_ffmpeg_impl->stream(img_);
#endif
  }

  void VideoStreamer::releaseImpl()
  {
#ifdef WITH_GSTREAMER
    this->_gstreamer_impl->gstreamerRelease();
#endif
#ifdef WITH_FFMPEG
    this->_ffmpeg_impl->stop();
#endif
  }

}
